"""
AI分析配置管理API接口
"""
from typing import Dict, Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field, validator
from enum import Enum
from datetime import datetime
import re

from core.database import get_db
from api.auth import get_current_active_user
from models.user import User
from models.analysis_task import TaskType
from services.ai_analysis_config_service import AIAnalysisConfigService
from core.exceptions import ConfigurationError

# 路由器
ai_analysis_config_router = APIRouter(prefix="/api/ai-analysis-config", tags=["AI分析配置"])


class AnalysisConfigType(str, Enum):
    """分析配置类型枚举"""
    REGIONAL_ANALYSIS = "RegionalAnalysis"
    COMPLAINT_TYPE_ANALYSIS = "ComplaintTypeAnalysis"
    SENTIMENT_ANALYSIS = "SentimentAnalysis"
    COMPLIANCE_ANALYSIS = "ComplianceAnalysis"
    DUPLICATE_ANALYSIS = "DuplicateAnalysis"


class RegionalAnalysisConfig(BaseModel):
    """区域分析配置模型"""
    analysis_levels: List[str] = Field(..., description="区域分析级别")
    region_codes: str = Field("", description="行政区划代码前缀")
    enable_coordinate_analysis: bool = Field(False, description="是否启用经纬度分析")
    prompt: str = Field(..., min_length=1, description="分析提示词")

    @validator('analysis_levels')
    def validate_analysis_levels(cls, v):
        valid_levels = ["地市", "区县", "街道"]
        for level in v:
            if level not in valid_levels:
                raise ValueError(f"无效的区域分析级别: {level}")
        return v


class ComplaintTypeAnalysisConfig(BaseModel):
    """信访类型分析配置模型"""
    prompt: str = Field(..., min_length=1, description="分析提示词")


class SentimentAnalysisConfig(BaseModel):
    """情感分析配置模型"""
    prompt: str = Field(..., min_length=1, description="分析提示词")


class ComplianceAnalysisConfig(BaseModel):
    """规范性分析配置模型"""
    prompt: str = Field(..., min_length=1, description="分析提示词")


class DuplicateAnalysisConfig(BaseModel):
    """重复信访分析配置模型"""
    filter_words: List[str] = Field(..., min_items=1, description="过滤词条")
    prompt: str = Field(..., min_length=1, description="分析提示词")

    @validator('filter_words')
    def validate_filter_words(cls, v):
        if len(v) > 10:
            raise ValueError("过滤词条数量不能超过10个")
        return [word.strip() for word in v if word.strip()]


class AnalysisConfigRequest(BaseModel):
    """分析配置请求模型"""
    config_type: AnalysisConfigType = Field(..., description="配置类型")
    config_data: Dict[str, Any] = Field(..., description="配置数据")

    @validator('config_data')
    def validate_config_data(cls, v, values):
        config_type = values.get('config_type')
        try:
            if config_type == AnalysisConfigType.REGIONAL_ANALYSIS:
                RegionalAnalysisConfig(**v)
            elif config_type == AnalysisConfigType.COMPLAINT_TYPE_ANALYSIS:
                ComplaintTypeAnalysisConfig(**v)
            elif config_type == AnalysisConfigType.SENTIMENT_ANALYSIS:
                SentimentAnalysisConfig(**v)
            elif config_type == AnalysisConfigType.COMPLIANCE_ANALYSIS:
                ComplianceAnalysisConfig(**v)
            elif config_type == AnalysisConfigType.DUPLICATE_ANALYSIS:
                DuplicateAnalysisConfig(**v)
            return v
        except Exception as e:
            # 提供更友好的错误信息
            error_msg = str(e)
            if "Field required" in error_msg:
                field_match = re.search(r"'([^']+)'", error_msg)
                if field_match:
                    field_name = field_match.group(1)
                    # 将字段名转换为中文提示
                    field_mapping = {
                        'analysis_levels': '区域分析级别',
                        'prompt': '分析提示词',
                        'filter_words': '过滤词条'
                    }
                    chinese_name = field_mapping.get(field_name, field_name)
                    raise ValueError(f"缺少必需字段: {chinese_name}")
            raise ValueError(f"配置数据验证失败: {error_msg}")


class AnalysisConfigResponse(BaseModel):
    """分析配置响应模型"""
    config_type: str
    config_data: Dict[str, Any]
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    is_active: bool = True


class ConfigTemplateResponse(BaseModel):
    """配置模板响应模型"""
    config_type: str
    template_name: str
    template_data: Dict[str, Any]
    description: str


@ai_analysis_config_router.get("/{task_type}", response_model=AnalysisConfigResponse)
async def get_analysis_config(
    task_type: str,
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    获取指定任务类型的分析配置
    """
    config_service = AIAnalysisConfigService(db)
    
    try:
        config_data = config_service.get_config(task_type)
        return AnalysisConfigResponse(
            config_type=task_type,
            config_data=config_data,
            is_active=True
        )
    except ConfigurationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@ai_analysis_config_router.post("/{task_type}", response_model=AnalysisConfigResponse)
async def create_or_update_analysis_config(
    task_type: str,
    config_request: AnalysisConfigRequest,
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    创建或更新分析配置
    """
    # 暂时移除类型检查，确保基本功能工作
    # TODO: 后续需要重新添加合适的类型验证
    print(f"INFO: 跳过类型检查，保存配置: {task_type}")
    
    config_service = AIAnalysisConfigService(db)
    
    try:
        success = config_service.save_config(task_type, config_request.config_data, current_user)
        if success:
            return AnalysisConfigResponse(
                config_type=task_type,
                config_data=config_request.config_data,
                updated_at=datetime.now(),
                is_active=True
            )
        else:
            raise HTTPException(status_code=500, detail="配置保存失败")
    except ConfigurationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"保存配置失败: {str(e)}")


@ai_analysis_config_router.delete("/{task_type}")
async def delete_analysis_config(
    task_type: str,
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    删除分析配置
    """
    config_service = AIAnalysisConfigService(db)
    
    try:
        success = config_service.delete_config(task_type)
        if success:
            return {"message": f"已删除 {task_type} 的配置"}
        else:
            raise HTTPException(status_code=500, detail="配置删除失败")
    except ConfigurationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除配置失败: {str(e)}")


@ai_analysis_config_router.get("/templates/{task_type}", response_model=List[ConfigTemplateResponse])
async def get_config_templates(
    task_type: str,
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    获取指定任务类型的配置模板
    """
    config_service = AIAnalysisConfigService(db)
    
    try:
        templates = config_service.get_config_templates(task_type)
        # 确保每个模板都有必需的字段
        response_templates = []
        for template in templates:
            response_template = {
                "config_type": task_type,
                "template_name": template.get("template_name", "默认模板"),
                "template_data": template.get("template_data", {}),
                "description": template.get("description", "配置模板")
            }
            response_templates.append(ConfigTemplateResponse(**response_template))
        return response_templates
    except ConfigurationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模板失败: {str(e)}")


@ai_analysis_config_router.post("/validate")
async def validate_analysis_config(
    config_request: AnalysisConfigRequest,
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    验证分析配置数据
    """
    config_service = AIAnalysisConfigService(db)

    try:
        # 处理配置类型 - 可能是枚举或字符串
        config_type = str(config_request.config_type.value) if hasattr(config_request.config_type, 'value') else str(config_request.config_type)
        result = config_service.validate_config(config_type, config_request.config_data)
        return {
            "valid": result["valid"],
            "message": result["message"],
            "config_type": config_type
        }
    except ConfigurationError as e:
        config_type = str(config_request.config_type.value) if hasattr(config_request.config_type, 'value') else str(config_request.config_type)
        return {
            "valid": False,
            "message": str(e),
            "config_type": config_type
        }
    except Exception as e:
        config_type = str(config_request.config_type.value) if hasattr(config_request.config_type, 'value') else str(config_request.config_type)
        return {
            "valid": False,
            "message": f"验证失败: {str(e)}",
            "config_type": config_type
        }


@ai_analysis_config_router.get("/list", response_model=List[AnalysisConfigResponse])
async def list_analysis_configs(
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    获取所有分析配置列表
    """
    config_service = AIAnalysisConfigService(db)
    
    try:
        configs = config_service.get_all_configs()
        return [
            AnalysisConfigResponse(
                config_type=config["task_type"],
                config_data=config["config_data"],
                is_active=config["is_configured"]
            ) for config in configs
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置列表失败: {str(e)}")


@ai_analysis_config_router.post("/batch-update")
async def batch_update_analysis_configs(
    configs: List[AnalysisConfigRequest],
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    """
    批量更新分析配置
    """
    config_service = AIAnalysisConfigService(db)
    
    try:
        # 转换为服务层需要的格式
        batch_configs = [
            {"task_type": config.config_type.value, "config_data": config.config_data}
            for config in configs
        ]
        
        result = config_service.batch_save_configs(batch_configs, current_user)
        
        # 转换响应格式
        updated_configs = []
        for i, config in enumerate(configs):
            status = "success" if result["results"][i]["status"] == "success" else "failed"
            updated_configs.append({
                "config_type": config.config_type.value,
                "status": status,
                "message": result["results"][i]["message"]
            })
        
        return {
            "updated_configs": updated_configs,
            "total_count": result["total_count"],
            "success_count": result["success_count"]
        }
    except ConfigurationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量更新失败: {str(e)}")